// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/functions/lib/aggregates/value_set.h>
#include <pollux/exec/container_row_serde.h>

namespace kumo::pollux::aggregate {
    void ValueSet::write(
        const BaseVector &vector,
        vector_size_t index,
        HashStringAllocator::Position &position) const {
        ByteOutputStream stream(allocator_);
        if (position.header == nullptr) {
            position = allocator_->newWrite(stream);
        } else {
            allocator_->extendWrite(position, stream);
        }

        static const exec::ContainerRowSerdeOptions options{};
        exec::ContainerRowSerde::serialize(vector, index, stream, options);
        allocator_->finishWrite(stream, 0);
    }

    StringView ValueSet::write(const StringView &value) const {
        if (value.isInline()) {
            return value;
        }

        const auto size = value.size();

        auto *header = allocator_->allocate(size);
        auto *start = header->begin();

        memcpy(start, value.data(), size);
        return StringView(start, size);
    }

    void ValueSet::read(
        BaseVector *vector,
        vector_size_t index,
        const HashStringAllocator::Header *header) const {
        POLLUX_CHECK_NOT_NULL(header);

        HashStringAllocator::InputStream stream(header);
        exec::ContainerRowSerde::deserialize(stream, index, vector);
    }

    void ValueSet::free(HashStringAllocator::Header *header) const {
        POLLUX_CHECK_NOT_NULL(header);
        allocator_->free(header);
    }

    void ValueSet::free(const StringView &value) const {
        if (!value.isInline()) {
            auto *header = HashStringAllocator::headerOf(value.data());
            allocator_->free(header);
        }
    }
} // namespace kumo::pollux::aggregate
